package com.toefl.speaking.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.toefl.speaking.model.UserInfo;
import com.toefl.speaking.util.AppConstans;
import com.toefl.speaking.util.AppUtils;

public class AuthHandler {

	private static AuthHandler instance;

	private Auth auth;

	private AuthHandler() {

	}

	public static AuthHandler instance() {
		if (instance == null) {
			instance = new AuthHandler();
		}
		return instance;
	}

	public Auth getAuth() {
		if (auth == null) {
			auth = new Auth();
		}
		return auth;
	}

	public void setAuth(Auth auth) {
		this.auth = auth;
	}

	public String postAuth(Auth auth, Context context) throws ClientProtocolException, IOException {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(AppConstans.DeviceToken, auth.getDeviceToken()));
		return AppUtils.httpPost(AppConstans.INTERFACE_URL+"auth", nameValuePairs);
	}

	public AuthResult getAuthResponseData(String jsonData) throws JSONException {
		AuthResult result = new AuthResult();
		JSONObject jsonObject = new JSONObject(jsonData);
		result.setStatus(Integer.parseInt(jsonObject.getJSONObject("Status").toString()));
		result.setErrorCode(Integer.parseInt(jsonObject.getJSONObject("ErrorCode").toString()));
		JSONObject jsonObjectSub = new JSONObject(jsonObject.getJSONObject("UserInfo").toString());
		UserInfo userInfo = new UserInfo();
		userInfo.setUid(Integer.parseInt(jsonObject.getJSONObject("Uid").toString()));
		userInfo.setEmail(jsonObjectSub.getJSONObject("Email").toString());
		userInfo.setName(jsonObjectSub.getJSONObject("Name").toString());
		result.setUserInfo(userInfo);
		return result;
	}

	public class Auth {
		private String DeviceToken;

		public String getDeviceToken() {
			return DeviceToken;
		}

		public void setDeviceToken(String deviceToken) {
			DeviceToken = deviceToken;
		}

	}

	public class AuthResult {

		private int Status;
		private int ErrorCode;
		private UserInfo userInfo;

		public int getStatus() {
			return Status;
		}

		public void setStatus(int status) {
			Status = status;
		}

		public int getErrorCode() {
			return ErrorCode;
		}

		public void setErrorCode(int errorCode) {
			ErrorCode = errorCode;
		}

		public UserInfo getUserInfo() {
			return userInfo;
		}

		public void setUserInfo(UserInfo userInfo) {
			this.userInfo = userInfo;
		}

	}

}
